package com.tiancheng.trade.commom.mq.rocket.autoconfigure;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.tiancheng.trade.commom.mq.rocket.RocketEnhanceProperties;
import com.tiancheng.trade.commom.mq.rocket.template.RocketMQEnhanceTemplate;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.messaging.converter.CompositeMessageConverter;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;

import java.util.List;

/**
 * @Author: likailun
 * @Description:
 * @Date: create in 2024/9/20 14:12
 */
@Configuration
@ConditionalOnProperty(name = "mq.type", havingValue = "rocket")
@ConditionalOnBean(RocketEnhanceProperties.class)
@EnableConfigurationProperties(RocketEnhanceProperties.class)
public class RocketMQEnhanceAutoConfiguration {

	@Resource()
	private RocketMQTemplate template;
	@Resource
	private RocketEnhanceProperties rocketEnhanceProperties;

	/**
	 * 注入增强的RocketMQEnhanceTemplate
	 */
	@Bean
	public RocketMQEnhanceTemplate rocketMQEnhanceTemplate(){
		return new RocketMQEnhanceTemplate(template,rocketEnhanceProperties);
	}

	/**
	 * 解决RocketMQ Jackson不支持Java时间类型配置
	 * 源码参考：{@link org.apache.rocketmq.spring.autoconfigure.MessageConverterConfiguration}
	 */
	@Bean
	@Primary
	public RocketMQMessageConverter enhanceRocketMQMessageConverter(){
		RocketMQMessageConverter converter = new RocketMQMessageConverter();
		CompositeMessageConverter compositeMessageConverter = (CompositeMessageConverter) converter.getMessageConverter();
		List<MessageConverter> messageConverterList = compositeMessageConverter.getConverters();
		for (MessageConverter messageConverter : messageConverterList) {
			if(messageConverter instanceof MappingJackson2MessageConverter){
				MappingJackson2MessageConverter jackson2MessageConverter = (MappingJackson2MessageConverter) messageConverter;
				ObjectMapper objectMapper = jackson2MessageConverter.getObjectMapper();
				objectMapper.registerModules(new JavaTimeModule());
			}
		}
		return converter;
	}


	/**
	 * 环境隔离配置
	 */
	@Bean
	public EnvironmentIsolationConfig environmentSetup(RocketEnhanceProperties rocketEnhanceProperties){
		return new EnvironmentIsolationConfig(rocketEnhanceProperties);
	}
}
